package com.outdd.vaietool.common.utils.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 邮件发送
 * @author vaie
 */
@Slf4j
public class EmailUtil {
    public static MimeMessage message;

    public static Boolean sendEmail(String email,String title,String content) {

        try {
            MimeMessageHelper msgHelper = EmailUtil.creatEmail();
            msgHelper.setTo(email);
            msgHelper.setSubject(title);
            msgHelper.setText(content);
            Transport.send(EmailUtil.message);
        }catch (Exception e){
            log.error("发送邮件失败",e);
            return false;
        }


        return true;
    }

    public static MimeMessageHelper creatEmail() throws MessagingException {
        String host = "smtp.163.com";
        String port= "465";
        String user ="edgeofeternity@163.com";
        String pw = "WBKHGOAJKPADDCIF";
// 创建Properties 类用于记录邮箱的一些属性
        final Properties props = new Properties();
// 表示SMTP发送邮件，必须进行身份验证
        props.put("mail.smtp.auth", "true");
//开启ttl加密
        props.put("mail.smtp.starttls.enable", "true");
//此处填写SMTP服务器
        props.put("mail.smtp.host", host);
//端口号，QQ邮箱给出了两个端口，但是另一个我一直使用不了，所以就给出这一个587
        props.put("mail.smtp.port", port);

        props.put("mail.smtp.ssl.enable", true);
// 此处填写你的账号
        props.put("mail.user", user);
// 此处的密码就是前面说的16位STMP口令
        props.put("mail.password", pw);

// 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
// 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
        message = new MimeMessage(mailSession);
        MimeMessageHelper helper = null;
// 设置发件人
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
        try {
            helper = new MimeMessageHelper(message, true, "utf-8");
            helper.setFrom(form);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return helper;
    }
}